import sqlite3
from flask import render_template, request, redirect, url_for, flash, session
from . import web_bp
from models import get_all_data_dictionaries, get_dictionary_items_by_dictionary_id, get_data_dictionary_by_code
from models import create_data_dictionary, create_dictionary_item, create_operation_log, get_db_connection

# 数据字典管理
@web_bp.route('/system/dictionaries')
def data_dictionaries():
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    dictionaries = get_all_data_dictionaries()
    return render_template('data_dictionaries.html', dictionaries=dictionaries)

# 添加数据字典
@web_bp.route('/system/dictionaries/add', methods=['GET', 'POST'])
def add_data_dictionary():
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    if request.method == 'POST':
        code = request.form['code']
        name = request.form['name']
        category = request.form['category']
        description = request.form['description']
        sort_order = request.form['sort_order']
        
        try:
            create_data_dictionary(code, name, category, description, sort_order)
            flash('字典添加成功')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '添加数据字典', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'code: {code}', '成功', 0)
        except Exception as e:
            flash(f'字典添加失败: {str(e)}')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '添加数据字典', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'code: {code}', f'失败: {str(e)}', 0)
        
        return redirect(url_for('web.data_dictionaries'))
    
    return render_template('add_data_dictionary.html')

# 编辑数据字典
@web_bp.route('/system/dictionaries/edit/<code>', methods=['GET', 'POST'])
def edit_data_dictionary(code):
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    dictionary = get_data_dictionary_by_code(code)
    if not dictionary:
        flash('字典不存在')
        # 记录操作日志
        create_operation_log(session['user_id'], session['username'], '更新数据字典', 
                            'POST', request.url, request.remote_addr, 
                            request.headers.get('User-Agent'), f'code: {code}', '字典不存在', 0)
        return redirect(url_for('web.data_dictionaries'))
    
    if request.method == 'POST':
        name = request.form['name']
        category = request.form['category']
        description = request.form['description']
        sort_order = request.form['sort_order']
        status = 1 if 'status' in request.form else 0
        
        conn = get_db_connection()
        cursor = conn.cursor()
        try:
            cursor.execute(
                'UPDATE data_dictionaries SET name=?, category=?, description=?, sort_order=?, status=? WHERE code=?',
                (name, category, description, sort_order, status, code)
            )
            conn.commit()
            flash('字典更新成功')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '更新数据字典', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'code: {code}', '成功', 0)
        except Exception as e:
            flash(f'字典更新失败: {str(e)}')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '更新数据字典', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'code: {code}', f'失败: {str(e)}', 0)
        finally:
            conn.close()
        
        return redirect(url_for('web.data_dictionaries'))
    
    return render_template('edit_data_dictionary.html', dictionary=dictionary)

# 数据字典项管理
@web_bp.route('/system/dictionaries/items/<int:dictionary_id>')
def dictionary_items(dictionary_id):
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    conn = get_db_connection()
    cursor = conn.cursor()
    dictionary = cursor.execute('SELECT * FROM data_dictionaries WHERE id=?', (dictionary_id,)).fetchone()
    conn.close()
    
    if not dictionary:
        flash('字典不存在')
        return redirect(url_for('web.data_dictionaries'))
    
    items = get_dictionary_items_by_dictionary_id(dictionary_id)
    return render_template('dictionary_items.html', dictionary=dictionary, items=items)

# 添加字典项
@web_bp.route('/system/dictionaries/items/add/<int:dictionary_id>', methods=['GET', 'POST'])
def add_dictionary_item(dictionary_id):
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    conn = get_db_connection()
    cursor = conn.cursor()
    dictionary = cursor.execute('SELECT * FROM data_dictionaries WHERE id=?', (dictionary_id,)).fetchone()
    conn.close()
    
    if not dictionary:
        flash('字典不存在')
        # 记录操作日志
        create_operation_log(session['user_id'], session['username'], '添加字典项', 
                            'POST', request.url, request.remote_addr, 
                            request.headers.get('User-Agent'), f'dictionary_id: {dictionary_id}', '字典不存在', 0)
        return redirect(url_for('web.data_dictionaries'))
    
    if request.method == 'POST':
        code = request.form['code']
        label = request.form['label']
        value = request.form['value']
        description = request.form['description']
        sort_order = request.form['sort_order']
        
        try:
            create_dictionary_item(dictionary_id, code, label, value, description, sort_order)
            flash('字典项添加成功')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '添加字典项', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'dictionary_id: {dictionary_id}, code: {code}', '成功', 0)
        except Exception as e:
            flash(f'字典项添加失败: {str(e)}')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '添加字典项', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'dictionary_id: {dictionary_id}, code: {code}', f'失败: {str(e)}', 0)
        
        return redirect(url_for('web.dictionary_items', dictionary_id=dictionary_id))
    
    return render_template('add_dictionary_item.html', dictionary=dictionary)